import React, {useState} from 'react';
import {Button, Input,Space} from 'antd';
import {CheckCircleOutlined, StopOutlined, PlusOutlined, EditOutlined, DeleteOutlined} from '@ant-design/icons';
import './Type.less'
import {Table, Modal} from 'antd';
import {Form, Radio, Select} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import http from "../../../utils/http";
import {useEffect} from 'react'
import { message} from 'antd';


const {Option} = Select;
const { confirm } = Modal;
// rowSelection objects indicates the need for row selection

function Type() {
    const getList=()=>{
        http({
            url: 'api/type/getTypeList',
            method: "post",
        }).then((res => {
            setData(res.data)
        }))
    }
    useEffect(()=>{
       getList()
    },[])
    const [checkStrictly, setCheckStrictly] = React.useState(false);
    //控制弹框
    const [visible1, setVisible1] = React.useState(false);
    const [visible2, setVisible2] = React.useState(false);
    const [visible3, setVisible3] = React.useState(false);
    const [visible4, setVisible4] = React.useState(false);
    //这是为了获得添加二级分类的时候所属一级分类id
    const [parentId, setParentId] = useState(0)
    // 这是为了获得修改一级分类的时候获得一级分类信息
    const [type1, setTypy1] = useState({})
    //二级分类
    const [type2, setTypy2] = useState({})
    //为了默认渲染修改弹框
    const [form1] = Form.useForm()
    const [form2] = Form.useForm()
    const [type1Name, setType1Name] = useState([])
    //选中的数据id集合
    const [id, setId] = useState([])
    const [type1AddValue, setType1AddValue] = useState("")
    const [type2AddValue, setType2AddValue] = useState("")
    const [type1UpdateValue, setType1UpdateValue] = useState({})
    const [type2UpdateValue, setType2UpdateValue] = useState({})
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            setId(selectedRowKeys)
        },
    };

    //表格信息
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            align: 'center',
            width: "15%"
        },
        {
            title: '分类名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
            width: "40%"
        },
        {
            title: '状态',
            dataIndex: 'state',
            key: 'state',
            align: 'center',
            width: "20%",
            render: (text, record) => (
                <button className='stateChange' onClick={() => {
                }}>
                    {record.status ? <CheckCircleOutlined style={{color: 'green'}}/> :
                        <StopOutlined style={{color: 'red'}}/>}
                </button>
            )
        },
        {
            title: '操作',
            dataIndex: 'control',
            key: 'control',
            align: 'center',
            render: (text, record) => (
                <div>
                    {record.level === 1 ? <button className='TypeControl' onClick={() => {
                        type2Add(record.id)
                    }}>
                        <PlusOutlined/>
                    </button> : ""}
                    <button className='TypeControl' onClick={() => {
                        record.level === 1 ? type1Update(record) : type2Update(record)
                    }}>
                        <EditOutlined/>
                    </button>
                    <button className='TypeControl' onClick={()=>{deleteThis(record.id)}}>
                        <DeleteOutlined/>
                    </button>
                </div>
            
            )
        },
    ];
    //分类数据
    let [data, setData] = useState([]);
    data.forEach(item => {
        item.key = item.id
        if (item.children) {
            item.children.forEach(i => {
                i.key = i.id
            })
        }
    })
    //一键启用
    const qiyongSelect=()=>{
        console.log("选中的数据id"+id)
        //    将选中id发给后台，成功后重新请求数据渲染页面
        http({
            url: 'api/type/updateTypeStatus',
            method: "post",
            data:{
                ids:id,
                status:1
            }
        }).then((res => {
            if (res.code==200){
                message.success('启用成功！');
                getList()
            }else {
                message.error('启用失败！');
            }
        }))
    }
    //一键禁用
    const jingyongSelect=()=>{
        console.log("选中的数据id"+id)
    //    将选中id发给后台，成功后重新请求数据渲染页面
        http({
            url: 'api/type/updateTypeStatus',
            method: "post",
            data:{
                ids:id,
                status:0
            }
        }).then((res => {
            if (res.code==200){
                message.success('禁用成功！');
                getList()
            }else {
                message.error('禁用失败！');
            }
        }))
    }
    //一键删除
    const deleteSelect=()=>{
        confirm({
            title: '确认删除吗？',
            icon: <ExclamationCircleOutlined />,
            // content: 'Some descriptions',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                console.log("选中的数据id"+id)
                http({
                    url: 'api/type/deleteType',
                    method: "post",
                    data:{
                        ids:id,
                    }
                }).then((res => {
                    if (res.code==200){
                        message.success('删除成功！');
                        getList()
                    }else {
                        message.error('删除失败！');
                    }
                }))
            },
            onCancel() {
                console.log('Cancel');
            },
        });
        //    将选中id发给后台，成功后重新请求数据渲染页面
    }
    //删除单个
    const deleteThis=(id)=>{
        let chooseId=[]
        chooseId.push(id)
        confirm({
            title: '确认删除吗？',
            icon: <ExclamationCircleOutlined />,
            // content: 'Some descriptions',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                console.log("数据id"+chooseId)
                http({
                    url: 'api/type/deleteType',
                    method: "post",
                    data:{
                        ids:chooseId,
                    }
                }).then((res => {
                    if (res.code==200){
                        message.success('删除成功！');
                        getList()
                    }else {
                        message.error('删除失败！');
                    }
                }))
            },
            onCancel() {
                console.log('Cancel');
            },
        });
        //    将选中id发给后台，成功后重新请求数据渲染页面
    }
    //一级分类添加弹框
    let type1Add = () => {
        setVisible1(true);
    }

    //一级分类添加弹框确认件
    const handleOk1 = () => {
        setVisible1(false);
        //确认发送请求，将type1AddValue发送给后台
        http({
            url: 'api/type/addType',
            method: "post",
            params:{
                level:1,
                name:type1AddValue,
                parentId:""
            }
        }).then((res => {
            if (res.code==200){
                message.success('添加成功！');
                getList()
            }else {
                message.error('添加失败！');
            }
        }))
        //成功后再次发送请求所有数据重新渲染页面
        setType2AddValue("")
    };
    //取消
    const handleCancel1 = () => {
        setVisible1(false);
        setType2AddValue("")
    };
    //二级分类添加
    let type2Add = (id) => {
        setVisible2(true);
        //得到此时父级id
        setParentId(id)
    }
    //二级添加确认
    const handleOk2 = () => {
        console.log(parentId,type2AddValue)
        setVisible2(false);
        //发送请求，父级id和type2AddValue值
        http({
            url: 'api/type/addType',
            method: "post",
            params:{
                level:2,
                name:type2AddValue,
                parentId:parentId
            }
        }).then((res => {
            if (res.code==200){
                message.success('添加成功！');
                getList()
            }else {
                message.error('添加失败！');
            }
        }))
        setType2AddValue("")
    };
    //取消
    const handleCancel2 = () => {
        setVisible2(false);
        setType2AddValue("")
    };
    //一级分类修改弹框
    let type1Update = (record) => {
        setVisible3(true);
        setType1UpdateValue(record)
        //默认渲染一级分类信息
        form1.setFieldsValue(record)
    }
    //一级分类修改确认
    const type1UpdateOk = () => {
        setVisible3(false);
        //提交
        form1.submit()
    };
    //一级修改表单提交获取表单信息
    const submit1 = (e) => {
        let data =type1UpdateValue
        data.name=e.name
        //
        // data.status=0
        // if (e.status==0){
        //     data.status=1
        // }
        http({
            url: 'api/type/updateType',
            method: "post",
            params:{
                id:data.id,
                name:data.name,
                level:1,
                status:e.status,
                parentId:""
            }
        }).then((res => {
            if (res.code==200){
                message.success('修改成功！');
                getList()
            }else {
                message.error('修改失败！');
            }
        }))
        console.log(type1UpdateValue)
    //    发送请求
    }
    //一级编辑取消
    const type1UpdateCancel = () => {
        setVisible3(false);
    };
    //二级修改
    let type2Update = (record) => {
        setVisible4(true);
        let type1Data = data
        let type2Data = record
        let type1Name1 = []
        type1Data.forEach((i) => {
            //一级分类名称集合
            type1Name1.push(i.name)
            if (type2Data.parentId == i.id) {
                //修改父级分类名称
                type2Data.parentName = i.name;
            }
        })
        setType2UpdateValue(type2Data)
        setType1Name(type1Name1)
        form2.setFieldsValue(type2Data)
    }
    //确认
    const type2UpdateOk = () => {
        setVisible4(false);
        form2.submit();
    };
    const submit2 = (e) => {
        let sendData = type2UpdateValue
        data.forEach(item => {
            if (e.parentName == item.name) {
                sendData.parentId = item.id
            }
        })
        sendData.status=e.status
        http({
            url: 'api/type/updateType',
            method: "post",
            params:{
                id:sendData.id,
                name:e.name,
                level:2,
                status:e.status,
                parentId:sendData.parentId
            }
        }).then((res => {
            if (res.code==200){
                message.success('修改成功！');
                getList()
            }else {
                message.error('修改失败！');
            }
        }))
        // console.log(type2UpdateValue)
    
        //    发送请求
    }
    //取消
    const type2UpdateCancel = () => {
        setVisible4(false);
    };
    return (
        <div id='goodsType'>
            <div className='typeBtn'>
                <Button type="primary" icon={<PlusOutlined/>} style={{backgroundColor: "#171c49"}} onClick={type1Add}>
                    新增
                </Button>
                <Button type="primary" icon={<CheckCircleOutlined/>} onClick={qiyongSelect}>
                    启用
                </Button>
                <Button type="primary" icon={<StopOutlined/>} style={{backgroundColor: "#ff9254"}} onClick={jingyongSelect}>
                    禁用
                </Button>
                <Button type="danger" icon={<DeleteOutlined/>} style={{backgroundColor: "#f56c6c"}}  onClick={deleteSelect}>
                    删除
                </Button>
            </div>
            <div className='typeSdata'>
                <Table
                    columns={columns}
                    rowSelection={{...rowSelection, checkStrictly}}
                    dataSource={data}
                    pagination={false}
                />
            </div>
            <>
                <Modal
                    title="添加一级分类"
                    visible={visible1}
                    onOk={handleOk1}
                    onCancel={handleCancel1}
                    cancelText='取消'
                    okText='确定'
                >
                    <span>分类名称：<Input
                        placeholder="请输入一级分类名称"
                        className='type1Input'
                        value={type1AddValue}
                        onChange={(ev) => {
                            setType1AddValue(ev.target.value)
                        }}/></span>
                </Modal>
            </>
            <>
                <Modal
                    title="添加二级分类"
                    visible={visible2}
                    onOk={handleOk2}
                    onCancel={handleCancel2}
                    cancelText='取消'
                    okText='确定'
                >
                    <span>分类名称：<Input
                        placeholder="请输入二级分类名称"
                        className='type1Input'
                        value={type2AddValue}
                        onChange={(ev) => {
                            setType2AddValue(ev.target.value)
                        }}
                    /></span>
                </Modal>
            </>
            <>
                <Modal
                    title="修改一级分类"
                    visible={visible3}
                    onOk={type1UpdateOk}
                    onCancel={type1UpdateCancel}
                    cancelText='取消'
                    okText='确定'
                >
                    <Form
                        onFinish={submit1}
                        form={form1}
                        initialValues={type1}
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 20,
                        }}
                        autoComplete="off"
                    >
                        
                        <Form.Item
                            label="分类名称"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            name="status"
                            label="选择状态："
                            rules={[
                                {
                                    required: true,
                                },
                            ]}>
                            <Radio.Group>
                                <Radio value={1}>启用</Radio>
                                <Radio value={0}>禁用</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </Form>
                </Modal>
            </>
            <>
                <Modal
                    title="修改二级分类"
                    visible={visible4}
                    onOk={type2UpdateOk}
                    onCancel={type2UpdateCancel}
                    cancelText='取消'
                    okText='确定'
                >
                    <Form
                        form={form2}
                        onFinish={submit2}
                        initialValues={type2}
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 20,
                        }}
                        autoComplete="off"
                    >
                        <Form.Item
                            name="parentName"
                            label="一级分类"
                            hasFeedback
                            rules={[{required: true}]}
                        >
                            <Select>
                                {type1Name.map((item, i) => {
                                    return (
                                        <Option key={i} value={item}>{item}</Option>
                                    )
                                })}
                            
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="分类名称"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            name="status"
                            label="选择状态："
                            rules={[
                                {
                                    required: true,
                                },
                            ]}>
                            <Radio.Group>
                                <Radio value={1}>启用</Radio>
                                <Radio value={0}>禁用</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </Form>
                </Modal>
            </>
        
        </div>
    )
}

export default Type